/*
 * Copyright (C) 2013 tangzhi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.tangzsoft.pdmviewer.utils;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author tangzhi
 */
public final class Utils {
    
    /**
     * 判断字串是否为空
     * @param str
     * @return 
     */
    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }
    
    
    /**
     * 打开文件
     * @param component
     * @param fileExt  可以访问的文件的后缀 example: {{"pdm","PDM file"}, {"*","All File"}}
     * @return 
     */
    public static File openFile(java.awt.Component component, final String[][] fileExts) {
        // TODO add your handling code here:
        JFileChooser fc = new JFileChooser();
        
        fc.setCurrentDirectory(new File("."));
        
        fc.setAcceptAllFileFilterUsed(false);
        
        for(final String[] fileExt: fileExts) {
            
            fc.addChoosableFileFilter(new FileFilter() {
                //Accept all directories and pdm files.
                @Override
                public boolean accept(File f) {
                    if (f.isDirectory()) {
                        return true;
                    }

                    String ext = null;
                    String s = f.getName();
                    int i = s.lastIndexOf('.');

                    if (i > 0 &&  i < s.length() - 1) {
                        ext = s.substring(i+1).toLowerCase();
                    }

                    if ("*".equals(fileExt[0]) || (ext != null&&ext.equals(fileExt[0])) ) {
                        return true;
                    }

                    return false;
                }

                //The description of this filter
                @Override
                public String getDescription() {
                    return fileExt[1];
                }
            });
            
        }
        
        int returnVal = fc.showOpenDialog(component);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            return fc.getSelectedFile();
        }
        
        return null;
        
    }

    public static ImageIcon createImageIcon(Class<?> parentClass, String path) {
        java.net.URL imgURL = parentClass.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            LogFactory.getLogger("org.tangzsoft.pdmviewer.utils")
                    .error("Couldn't find file: {}" , path);
            return null;
        }
    }
    
    public static Object getValue(Object obj, String field) {
        Method[] methods = obj.getClass().getMethods(); 
        
        for(int i=0; i<methods.length;i++){   
            try {
                //取方法名   
                String method = methods[i].getName();
                
                if( !method.startsWith("get") 
                        || methods[i].getParameterTypes().length!=0) {
                    continue;
                }
                
                String key = method.substring(3);
                
                if (!key.equalsIgnoreCase(field)) {
                    continue;
                }
                
                return methods[i].invoke(obj);
                
            } catch (IllegalAccessException ex) {
                LogError(null, ex);
            } catch (IllegalArgumentException ex) {
                LogError(null, ex);
            } catch (InvocationTargetException ex) {
                LogError(null, ex);
            }
        }
        
        return null;
    }
    
    public static Object map2Bean(Map map, Class<?> cls) {
        Object obj = null;
        try {
            obj = cls.newInstance();
        } catch (InstantiationException ex) {
            LogError(null, ex);
        } catch (IllegalAccessException ex) {
            LogError(null, ex);
        }
        
        Method[] methods = cls.getMethods();   
        for(int i=0; i<methods.length;i++){   
            try {
                //取方法名   
                String method = methods[i].getName();
                
                if( !method.startsWith("set") 
                        || methods[i].getParameterTypes().length!=1) {
                    continue;
                }
                
                String key = method.substring(3);
                
                if (!map.containsKey(key)) {
                    continue;
                }
                
                methods[i].invoke(obj, map.get(key));
                
            } catch (IllegalAccessException ex) {
                LogError(null, ex);
            } catch (IllegalArgumentException ex) {
                LogError(null, ex);
            } catch (InvocationTargetException ex) {
                LogError(null, ex);
            }
        }
            
        return obj;
    }
    
    private static void LogError(String str, Exception ex) {
        LogFactory.getLogger("org.tangzsoft.pdmviewer.utils")
                    .error(str, ex);
    }
}
